def short_name:
  {
    "qty_ticksize": "qtic",
    "price_ticksize": "ptic",
    "min_qty": "mqty",
    "min_amount": "mamt"
  }[.]
;

def check_upd_symbol_price_ticksize:
  .[0].mea as $mea |
  .[0].product_infos + .[1].product_infos |
  group_by(.symbol) | map(select(length == 2)) |
  map(select(.[0].price_ticksize != .[1].price_ticksize)) |
  map(.[0].symbol) | {"type": "UPDATE", "mea": $mea, "symbols": ., "info": ("price_ticksize" | short_name)}
;

def check_upd_symbol_qty_ticksize:
  .[0].mea as $mea |
  .[0].product_infos + .[1].product_infos |
  group_by(.symbol) | map(select(length == 2)) |
  map(select(.[0].qty_ticksize != .[1].qty_ticksize)) |
  map(.[0].symbol) | {"type": "UPDATE", "mea": $mea, "symbols": ., "info": ("qty_ticksize" | short_name)}
;

def check_upd_symbol_min_qty:
  .[0].mea as $mea |
  .[0].product_infos + .[1].product_infos |
  group_by(.symbol) | map(select(length == 2)) |
  map(select(.[0].min_qty != .[1].min_qty)) |
  map(.[0].symbol) | {"type": "UPDATE", "mea": $mea, "symbols": ., "info": ("min_qty" | short_name)}
;


def check_new_symbol:
  .[0].mea as $mea |
  [.[0].product_infos[] | .symbol] as $new |
  [.[1].product_infos[] | .symbol] as $old |
  $new - $old | {"type": "ADD", "mea": $mea, "symbols": ., "info": ""}
;


def check_del_symbol:
  .[0].mea as $mea |
  [.[0].product_infos[] | .symbol] as $new |
  [.[1].product_infos[] | .symbol] as $old |
  $old - $new | {"type": "REMOVE", "mea": $mea, "symbols": ., "info": ""}
;

def flatten_each:
  [(.symbols | .[] ) as $s | {"mea": .mea, "symbol": $s, "type": .type, "info": .info}]
;

def get_pi_update:
  [add | group_by(.mea) | map(check_new_symbol) | map(select(.symbols | length > 0))] +
  [add | group_by(.mea) | map(check_del_symbol) | map(select(.symbols | length > 0))] +
  [add | group_by(.mea) | map(check_upd_symbol_price_ticksize) | map(select(.symbols | length > 0))] +
  [add | group_by(.mea) | map(check_upd_symbol_qty_ticksize) | map(select(.symbols | length > 0))] +
  [add | group_by(.mea) | map(check_upd_symbol_min_qty) | map(select(.symbols | length > 0))]
;

def get_pi_update_tbl:
  [add | .[] | flatten_each] | add | ["mea", "symbol", "type", "info"] as $keys | map([.[ $keys[] ]])[] | @csv
;
